package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.zb.client.SkuFeignClient;
import com.zb.dto.SkuDTO;
import com.zb.dto.SpuDTO;
import com.zb.entity.TbOrderItemModel;
import com.zb.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SkuFeignClient skuFeignClient;

    @Override
    public Boolean addItem(String id, Integer num, String uname) {
        if (num <= 0) {
            // key     hash - key:value
            redisTemplate.boundHashOps("cart:" + uname).delete(id);
        }
        Map<String, Object> skuDetailMap = skuFeignClient.item(id);
        Map<String, Object> skuMap = (Map<String, Object>) skuDetailMap.get("skuDTO");
        Map<String, Object> spuMap = (Map<String, Object>) skuDetailMap.get("spuDTO");
        SkuDTO skuDTO = JSON.parseObject(JSON.toJSONString(skuMap), SkuDTO.class);
        SpuDTO spuDTO = JSON.parseObject(JSON.toJSONString(spuMap), SpuDTO.class);
        TbOrderItemModel orderItemModel = new TbOrderItemModel();
        orderItemModel.setCategoryId1(spuDTO.getCategory1Id());
        orderItemModel.setCategoryId2(spuDTO.getCategory2Id());
        orderItemModel.setCategoryId3(spuDTO.getCategory3Id());
        orderItemModel.setSpuId(spuDTO.getId());
        orderItemModel.setSkuId(skuDTO.getId());
        orderItemModel.setName(skuDTO.getName());
        orderItemModel.setPrice(skuDTO.getPrice());
        orderItemModel.setNum(num);
        orderItemModel.setMoney(skuDTO.getPrice() * num);
        orderItemModel.setImage(skuDTO.getImage());
        orderItemModel.setWeight(skuDTO.getWeight());
        redisTemplate.boundHashOps("cart:" + uname).put(id, orderItemModel);
        return true;
    }

    @Override
    public List<TbOrderItemModel> list(String uname) {
        return redisTemplate.boundHashOps("cart:" + uname).values();
    }

    @Override
    public Boolean remove(String username, String skuId) {
        return redisTemplate.boundHashOps("cart:" + username)
                .delete(skuId) > 0 ? true : false;
    }

    @Override
    public List<TbOrderItemModel> select(String username, String[] skuIds) {
        List<TbOrderItemModel> list = new ArrayList<>();
        for (String skuId : skuIds) {
            list.add((TbOrderItemModel) redisTemplate.boundHashOps("cart:" + username).get(skuId));
        }
        return list;
    }
}
